package com.flyco.modules.oms.handle.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flyco.common.constant.SfStatus;
import com.flyco.common.util.HttpUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.oms.entity.OmsOrderTrace;
import com.flyco.modules.oms.handle.ISyncLogisticsHandle;
import com.flyco.modules.oms.mapper.OmsOrderTraceMapper;
import com.flyco.modules.oms.model.OmsOrderSfTraceModel;
import com.flyco.modules.oms.service.IOmsOrderAdditionService;
import com.flyco.modules.util.ApiUtil;
import com.flyco.modules.util.VerifyCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 同步顺丰物流轨迹
 */
@Slf4j
@Component("logisticsHandle-顺丰")
public class SyncLogisticsSfHandleImpl implements ISyncLogisticsHandle {
    @Autowired
    private OmsOrderTraceMapper omsOrderTraceMapper;
    @Autowired
    private IOmsOrderAdditionService omsOrderAdditionService;

    @Override
    public void syncLogistics(String billcode, String orderId) {
        log.info("开始同步顺丰物流单号 :" + billcode);
        JSONArray billData = new JSONArray();
        billData.add(billcode);

        JSONObject msgDataJson = new JSONObject();
        msgDataJson.put("language", 0);
        msgDataJson.put("trackingType", 1);
        msgDataJson.put("trackingNumber", billData);
        msgDataJson.put("methodType", 1);

        String timeStamp = String.valueOf(System.currentTimeMillis());
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("partnerID", ApiUtil.getPartnerID());
        parameters.put("requestID", UUID.randomUUID().toString().replace("-", ""));
        parameters.put("serviceCode", "EXP_RECE_SEARCH_ROUTES");
        parameters.put("timestamp", timeStamp);
        parameters.put("msgData", msgDataJson.toJSONString());
        parameters.put("msgDigest", getMsgDigest(msgDataJson.toJSONString(), timeStamp, ApiUtil.getCheckword()));

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        String result = HttpUtil.postRequest(ApiUtil.getSfUrl(), headers, parameters);
        log.info("result:" + result);

        if (! oConvertUtils.isEmpty(result)) {
            JSONObject resultJson = JSON.parseObject(result).getJSONObject("apiResultData");
            if (Objects.equals(resultJson.get("success"), true)) {
                JSONArray dataArray = resultJson.getJSONObject("msgData").getJSONArray("routeResps");
                for(int i=0; i<dataArray.size(); i++){
                    JSONObject resultObj = dataArray.getJSONObject(i);
                    String traceCode = resultObj.getString("mailNo");
                    JSONArray jsonArray = resultObj.getJSONArray("routes");
                    log.info("jsonArray:" + jsonArray);
                    if (null != jsonArray && jsonArray.size() > 0) {
                        List<OmsOrderSfTraceModel> addModels = new ArrayList<>();
                        Integer dbCount = omsOrderTraceMapper.getCountByTraceNo(billcode);
                        List<OmsOrderSfTraceModel> models = jsonArray.toJavaList(OmsOrderSfTraceModel.class);
                        // todo 使用顺丰的默认排序，把按时间排序注释 2021-4-1
                        //Collections.sort(models, Comparator.comparing(OmsOrderSfTraceModel::getCreateTime));
                        if (jsonArray.size() > dbCount) {
                            addModels = models.subList(dbCount, models.size());
                        }
                        //log.info("addModels:" + addModels);
                        List<OmsOrderTrace> traces = new ArrayList<>();
                        for (OmsOrderSfTraceModel traceModel : addModels) {
                            OmsOrderTrace trace = new OmsOrderTrace();
                            BeanUtils.copyProperties(traceModel, trace);
                            if ( oConvertUtils.isNotEmpty(traceModel.getScanSite()) ) {
                                trace.setContent( "【" + traceModel.getScanSite() + "】" + trace.getContent() );
                            }
                            trace.setTraceNo(traceCode);
                            if (oConvertUtils.isNotEmpty(SfStatus.fromName("_"+traceModel.getLabel()))) {
                                trace.setLabel(SfStatus.fromName("_"+traceModel.getLabel()).getStatusValue());
                            } else {
                                trace.setLabel("运送中");
                            }
                            omsOrderTraceMapper.insert(trace);
                        }

                        OmsOrderSfTraceModel traceModel =  models.get(models.size() - 1);
                        String sign = "80,8000";
                        if(oConvertUtils.isNotEmpty(traceModel.getLabel()) && Arrays.asList(sign.split(",")).contains(traceModel.getLabel())) {
                            // TODO: 2020/4/8 处理订单签收
                            omsOrderTraceMapper.updateOrderSigned(orderId, billcode, traceModel.getCreateTime());
                            try {
                                omsOrderAdditionService.afterSign(orderId);
                            } catch (Exception e) {
                                log.error(e.getMessage());
                            }
                        }
                    }
                }
            }
        }
    }


    public static String getMsgDigest(String msgData, String timeStamp, String md5Key) {
        try {
            return VerifyCodeUtil.md5EncryptAndBase64(URLEncoder.encode(String.valueOf(msgData) + timeStamp + md5Key, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
}
